<template>
  <div>
    <el-progress
      v-if="isUploading"
      type="circle"
      :percentage="percentage"
      :status="percentage===100?'success':undefined" />
    <el-upload
      v-else
      class="avatar-uploader"
      action="course/upload"
      :show-file-list="false"
      :http-request="handleUpload"
      :before-upload="beforeAvatarUpload">
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { uploadCourseImg } from '@/services/course'
export default {
  props: {
    value: String
  },

  data () {
    return {
      isUploading: false,
      percentage: 0
    }
  },

  methods: {
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleUpload (options) {
      const fd = new FormData()
      fd.append('file', options.file)
      this.percentage = 0
      this.isUploading = true
      uploadCourseImg(fd, e => {
        this.percentage = Math.floor(e.loaded / e.total * 100)
      }).then(res => {
        this.$emit('input', res.data.data.name)
        console.log(res.data.data)
      }).finally(() => {
        this.isUploading = false
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.avatar-uploader ::v-deep.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep.el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
